/**
 * Created by txh on 2019/7/10.
 */
import React,{Component} from 'react'
import { Alert,Icon,Popover,Table, Button ,Tooltip,Tag, Tabs,Modal} from 'antd';
import {getPageSize, getPageStartIndex} from "../util/WtTableCommon";
import WtHostPost from "../util/WtHostPost";
import WtNotification from "../util/WtNotification";

class WtUserBooks extends Component{
    constructor(props){
        super(props)
        this.state={
            selectedRowKeys: [], // Check here to configure the default column
            loading: false,
            pagination:{showSizeChanger:false,pageSizeOptions:['10','20','50','100'],current:1},
            data:[],
            bookInfo:null,
            changeVisible:false,
            tabIndex : '1',
            detailVisible: false,
            searchValue : '',

            value:null
        }

        this.colsKey={

            isbn:{
                title:'ISBN码',
                key:'isbn',
                width:100,
                render:(text,record)=>{
                    return (
                        record.book.isbn
                    )
                }
            },
            bookType:{
                title:'图书类型',
                key:'bookType',
                width:100,
                render:(text,record)=>{
                    return (
                        record.book.bookType
                    )
                }
            },
            bookName:{
                title:'图书名称',
                key:'bookName',
                width:100,
                render:(text,record)=>{
                    return (
                        record.book.bookName
                    )
                }
            },
            authorName:{
                title:'作者名称',
                key:'authorName',
                width:100,
                render:(text,record)=>{
                    return (
                        record.book.authorName
                    )
                }
            },
            publisher:{
                title:'出版社',
                key:'publisher',
                width:100,
                render:(text,record)=>{
                    return (
                        record.book.publisher
                    )
                }
            },
            operation:{
                title:'操作',
                key:'operation',
                width:110,
                render:(text,record)=>{
                    return (
                        <div className="operation">
                            <Tooltip title="详情">
                                <a className="operation-button primary" onClick={()=>{this.setState({detailVisible:true,value:record})}}>详情</a>
                            </Tooltip>
                            <span>|</span>
                            <Tooltip title="归还">
                                {
                                    record.state === 1 ?
                                        <a className="operation-button no-primary" onClick={()=>{this.handleBack(record.book.isbn)}}>归还</a> :
                                        (
                                            record.book.isNum > 0 ?
                                                <a className="operation-button no-primary" onClick={()=>{this.handleBorrow(record.book)}}>再次借阅</a> :
                                                <a className="operation-button no-primary" style={{color:'grey'}} onClick={()=>{}}>再次借阅</a>
                                        )
                                }
                            </Tooltip>
                        </div>
                        // record.operation
                    )
                }
            },
        }
    }
    //初始化
    componentDidMount() {
        this.handleRefresh();
    }


    //fetch 函数去后台取数据，数据的格式是json格式
    fetch=(params={})=>{
        params['type'] = parseInt(this.state.tabIndex);
        this.setState({loading:true});
        WtHostPost("/user-book-get",{...params},true).then(({json}) => {
            if (json.code === 0){
                this.setState({loading:false,data:json.data});
                let pagination = this.state.pagination;
                pagination.total = json.total;
                this.setState({pagination});
            }else {
                throw json;
            }
        }).catch(err=>{
            WtNotification.error("添加订单失败");
            this.setState({loading:false});
        })
    }
    handleBorrow = (record)=>{
        if (record.isNum <= 0){
            WtNotification.error("该书籍已被借空");
            return;
        }
        WtHostPost("/borrow",{isbn:record.isbn},true).then(({json}) => {
            if (json.code === 0){
                this.handleRefresh();
            }else {
                throw json;
            }
        }).catch(err=>{
            WtNotification.error(err.msg);
        })
    }

    handleBack = (isbn)=>{
        WtHostPost("/reback",{isbn},true).then(({json}) => {
            if (json.code === 0){
                this.handleRefresh();
            }else {
                throw json;
            }
        }).catch(err=>{
            WtNotification.error("归还失败");
        })
    }


//界面有刷新的时候
    handleRefresh = ()=>{
        let offset =getPageStartIndex(this.state.pagination);
        let limit = getPageSize(this.state.pagination)
        this.fetch({offset,limit})
    }

    handleTableChange=(key)=> {
        console.log(key);
        this.setState({tabIndex:key},()=>{
            this.handleRefresh()
        })
    }

    getColumns=()=>{
        let cols=[];
        cols.push(this.colsKey.isbn);
        cols.push(this.colsKey.bookType);
        cols.push(this.colsKey.bookName);
        cols.push(this.colsKey.authorName);
        cols.push(this.colsKey.publisher);
        cols.push(this.colsKey.operation);
        return cols;
    };

    onSelectChange = selectedRowKeys => {
        this.setState({ selectedRowKeys });
    };

    handleSearch = (value) => {

        this.setState({searchValue:value},()=>{
            this.handleRefresh();
        })
    }

    renderDataContainers(){
        const {selectedRowKeys} = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        return(
            <div>

                <div style={{marginTop:10}}>
                    <div style={{textAlign:'right',marginBottom:10}} className="content-col">
                        <span><Tooltip title="在馆"><Tag className="wt-tag-shadow" color="#87d068" style={{width: 40}}/></Tooltip> <span>在馆</span></span>
                        <span><Tooltip title="借空"><Tag className="wt-tag-shadow" color="#999db1" style={{width: 40}}/></Tooltip> <span>借空</span></span>
                    </div>
                    <Alert
                        message={
                            <span>
                                你选中了{this.state.selectedRowKeys.length}条数据(
                                <a onClick={() => {this.setState({selectedRowKeys:[]})}}>重选</a>),
                                <span style={{float:'right'}}>
                                    <a onClick={this.handleRefresh} style={{padding:'0 6px'}}>刷新</a>
                                </span>
                            </span>
                        }
                        type="info"
                        icon={<Icon type="info-circle" />}
                    />
                    <Table style={{textAlign:'center'}}
                           className="wt-task-table wt-ant-table wt-long-text"
                           size="small"
                           columns={this.getColumns()}
                           rowSelection={rowSelection}
                           rowKey={record => record.id}
                           dataSource={this.state.data}
                           pagination={this.state.pagination}
                           loading={this.state.loading}
                           onChange={this.handleTableChange}
                    />
                </div>
            </div>
        )
    }


    render() {
        const { TabPane } = Tabs;
        const {value} = this.state;
        return (
            <div>
                <h2>我的借阅</h2>
                <Tabs value={this.state.tabIndex} onChange={this.handleTableChange}>
                    <TabPane tab="正在借阅" key="1" />
                    <TabPane tab="已经归还" key="2"/>
                    <TabPane tab="全部图书" key="3"/>
                </Tabs>
                {this.renderDataContainers()}
                {
                    this.state.detailVisible &&
                    <Modal
                        visible={this.state.detailVisible}
                        title="Title"
                        onOk={()=>{this.setState({detailVisible:false})}}
                        onCancel={()=>{this.setState({detailVisible:false})}}
                        footer={[
                            <Button key="back" onClick={this.handleCancel}>
                                返回
                            </Button>,
                            <Button key="submit" type="primary" onClick={()=>{this.setState({detailVisible:false})}}>
                                确认
                            </Button>,
                        ]}
                    >
                        <p>isbn:{value.book.isbn}</p>
                        <p>作者:{value.book.authorName}</p>
                        <p>书名:{value.book.bookType}</p>
                        <p>书籍类型:{value.book.bookType}</p>
                        <p>上架日期:{value.book.date}</p>
                        <p>在馆数量:{value.book.isNum}</p>
                        <p>价格:{value.book.price}</p>
                        <p>出版社:{value.book.publisher}</p>
                        <p>借阅时间:{value.borrowTime}</p>
                    </Modal>
                }
            </div>
        );
    }
}



export default WtUserBooks;
